<template>
  <div class="component-root">
    <el-card>
      <p slot="header">
        <span><b>用户协议</b></span>
        <el-button type="primary" class="base-el-float-right" @click="handleUpdate('用户协议')">更新</el-button>
      </p>

      <el-input v-model="userAgreement" type="textarea" :autosize="{ minRows: 2, maxRows: 20}" />
    </el-card>
    <el-card>
      <p slot="header">
        <span><b>隐私政策</b></span>
        <el-button type="primary" class="base-el-float-right" @click="handleUpdate('隐私政策')">更新</el-button>
      </p>

      <el-input v-model="policy" type="textarea" :autosize="{ minRows: 2, maxRows: 20}" />
    </el-card>
  </div>
</template>
<script>

import { queryByCondition, updateById } from '@/api/commoncrud'
export default {
  name: 'UserAgreementContent',
  data() {
    return {
      userAgreementId: '',
      userAgreement: '',
      policyId: '',
      policy: ''
    }
  },
  async mounted() {
    await this.fetchData()
  },
  methods: {
    async fetchData() {
      const protocolRes = await queryByCondition('globalconfig', 0, 1, { name: 'user_protocol' })
      const policyRes = await queryByCondition('globalconfig', 0, 1, { name: 'user_policy' })

      const protocol = protocolRes.data.documentList[0]
      const policy = policyRes.data.documentList[0]

      this.userAgreementId = protocol._id
      this.userAgreement = protocol.data

      this.policyId = policy._id
      this.policy = policy.data
    },
    async handleUpdate(title) {
      this.$alert(`确认更新${title}?`, '消息提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        showCancelButton: true,
        callback: async action => {
          if (action === 'confirm') {
            if (title === '用户协议') {
              await updateById('globalconfig', this.userAgreementId, { data: this.userAgreement })
            } else {
              await updateById('globalconfig', this.policyId, { data: this.policy })
            }
            this.$message.success('更新成功!')
            await this.fetchData()
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.component-root{
  margin: 20px;
}
.margin-right{
  margin-right: 20px;
}
</style>
